//
//  aa_bbPlatform_aa_bb.m
//  kratos_framework_Example
//
//  Created by 7yao.top on 2018/10/22.
//  Copyright © 2018年 kratos_framework. All rights reserved.
//

#import "Kratos_Platform.h"
#import "Kratos_account_bb_aa.h"
#import "Kratos_MainViewController.h"
#import "Kratos_HttpConfigure.h"
#import "Kratos_Options.h"
#import "Kratos_Tool.h"
#import <AdSupport/AdSupport.h>
#import "Kratos_SDKInitPresenter_Kra.h"
#import "DCTrackingAgent.h"
#import "Kratos_LongZhuLogin.h"
#import "Kratos_MenuViewController.h"
#import "Kratos_FloatWindow.h"
#import "Kratos_userInfo.h"
#import "Kratos_AppleIAP_Kra.h"
#import "MBProgressHUD+HUD.h"
#import "NNN_CallView_nnn.h"
#import "Kratos_userInfo.h"
#import "Kratos_CallViewController.h"
#import "Kratos_bandingVC.h"
#import "YYModel.h"


@interface Kratos_Platform () 
@property (strong,nonatomic)  Kratos_FloatWindow *floatWindow;
//YunView
@property (nonatomic,strong) NNN_CallView_nnn *NNN_callPageView_nnn;
@end

@implementation Kratos_Platform
static id _instance = nil;

- (void)Kratos_ShowAccountViewController:(UIViewController *)viewController Kratos_delegate:(id <Kratos_PlatformDelegate>)delegate Kratos_options:(Kratos_Options*)option
{
    self.weak_viewController = viewController;
    self.delegate = delegate;
    
     //更改WK UserAgent
    [Kratos_Tool Kratos_ModifyUserAgent_ggg];
    
    ///监听登录成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kratos_getUserInfo:) name:Kra_kLoginSuccessNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kratos_logoutFromSDK:) name:Kra_kLogoutSDKNotification object:nil];
    Kratos_HttpConfigure *configure =   [Kratos_HttpConfigure sharedHttpConfigure];
    configure.Kra_option = option;
    
    

    
    
    

}
- (void)showFloadWindouw
{
    
    __weak typeof(self) weakSelf = self;
//    _floatWindow =  [[Kratos_FloatWindow alloc]initWithFrame:CGRectMake(0, 100, 50, 50) Kratos_mainImageName:@"z" Kratos_imagesAndTitle:@{@"float_gift":@"用户中心",@"float_logout":@"退出登录",@"float_service":@"客服中心",@"float_update":@"账号升级"} Kratos_bgcolor:[UIColor whiteColor] Kratos_animationColor:[UIColor whiteColor]];
//    _floatWindow.clickBolcks = ^(NSInteger i,NSString *currentTitle) {
//        if ([currentTitle isEqualToString:@"用户中心"]) {
//            //用户中心
//
//            Kratos_MenuViewController * vc = [[Kratos_MenuViewController alloc]init];
//            [weakSelf.weak_viewController presentViewController:vc animated:false completion:nil];
//
//        }
//    };
    
    
    
    _floatWindow =  [[Kratos_FloatWindow alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width -30, 100, 50, 50) Kratos_mainImageName:@"z" Kratos_imagesAndTitle:@{@"float_gift":@"绑定手机",@"float_logout":@"退出登录"} Kratos_bgcolor:[UIColor whiteColor] Kratos_animationColor:[UIColor whiteColor]];
    _floatWindow.clickBolcks = ^(NSInteger i,NSString *currentTitle) {
        if ([currentTitle isEqualToString:@"用户中心"]) {
            //用户中心
            Kratos_MenuViewController * vc = [[Kratos_MenuViewController alloc]init];
            [weakSelf.weak_viewController presentViewController:vc animated:false completion:^{
              vc.view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
            }];
            
        }else if ([currentTitle isEqualToString:@"绑定手机"])
        {
            Kratos_bandingVC * vc = [[Kratos_bandingVC alloc]init];
            [weakSelf.weak_viewController presentViewController:vc animated:false completion:nil];
        }else if ([currentTitle isEqualToString:@"退出登录"])
        {
            
            [weakSelf logoutAction];
        }
    };
    
}
- (void)Kratos_showloginView
{
//    NSString * InitCallBack = [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
//      if ([InitCallBack isEqualToString:@"NO"])
//    {
//
//        NSDictionary *temp = @{
//                               @"chid": @"24:578290:1547727300:1",
//                               @"id" :@"490400",
//                               @"instime"  : @"1547727312",
//                               @"logflag" : @"0",
//                               @"nickname" : @"4071c715341",
//                               @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
//                               @"token":@"3680b310eec59b0366ef75aa1edbe86e",
//                               @"type":@"7",
//                               @"username" : @"4071c715341"
//                               };
//        [self.delegate kratos_getUserInfo:temp];
//
//
//    }else
//    {
//        [self addChilidVC];
//        _floatWindow.hidden = true;
//        _floatWindow = nil;
//    }

    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == false) {
        NSDictionary *temp = @{
                               @"chid": @"24:578290:1547727300:1",
                               @"id" :@"490400",
                               @"instime"  : @"1547727312",
                               @"logflag" : @"0",
                               @"nickname" : @"4071c715341",
                               @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
                               @"token":@"3680b310eec59b0366ef75aa1edbe86e",
                               @"type":@"7",
                               @"username" : @"4071c715341"
                               };
        [self.delegate kratos_getUserInfo:temp];
        
        
    }else
    {
        [self addChilidVC];
        _floatWindow.hidden = true;
        _floatWindow = nil;
    }
   
}

- (void)logoutAction
{
//    [Kratos_userInfo Kratos_loginOut];
    [self addChilidVC];
    _floatWindow.hidden = true;
    _floatWindow = nil;
    if ([self.delegate respondsToSelector:@selector(kratos_logoutFromSDK)]) {
        [self.delegate kratos_logoutFromSDK];

    }
}
- (void)Kratos_showFloatoraddChilidVC
{
    
//     NSString * InitCallBack = [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
//
//    if ([Kratos_userInfo Kratos_getCurrentUserInfo_Kratos] != nil || [InitCallBack isEqualToString:@"NO"])
//    {
////        [self showFloadWindouw];
//        NSDictionary *temp =@{
//                              @"chid": @"24:578290:1547727300:1",
//                              @"id" :@"490400",
//                              @"instime"  : @"1547727312",
//                              @"logflag" : @"0",
//                              @"nickname" : @"4071c715341",
//                              @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
//                              @"token":@"3680b310eec59b0366ef75aa1edbe86e",
//                              @"type":@"7",
//                              @"username" : @"4071c715341"
//                              };
//        [self.delegate kratos_getUserInfo:temp];
//        return;
//    }
    
    
//    NSString * InitCallBack = [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
    
    if ([Kratos_userInfo Kratos_getCurrentUserInfo_Kratos] != nil || [Kratos_Tool Kratos_getCallback_Kratos] == false)
    {
        //        [self showFloadWindouw];
        NSDictionary *temp =@{
                              @"chid": @"24:578290:1547727300:1",
                              @"id" :@"490400",
                              @"instime"  : @"1547727312",
                              @"logflag" : @"0",
                              @"nickname" : @"4071c715341",
                              @"thumb" : @"https://preios_28_1.luckystar001.top/static/common/images/boy.jpg",
                              @"token":@"3680b310eec59b0366ef75aa1edbe86e",
                              @"type":@"7",
                              @"username" : @"4071c715341"
                              };
        [self.delegate kratos_getUserInfo:temp];
        return;
    }
    
    
    
    
    if ([Kratos_userInfo Kratos_getCurrentUserInfo_Kratos] == nil)
    { //不存在用户数据，现实登录界面
        [self addChilidVC];
    }else
    {
        Kratos_userInfo *user = [Kratos_userInfo Kratos_getCurrentUserInfo_Kratos];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"chid"] = user.Kra_chid;
        dict[@"fuid"] = user.Kra_fuid;
        dict[@"gender"] = user.Kra_gender;
        dict[@"id"] = user.Kra_ID;
        dict[@"instime"] = user.Kra_instime;
        dict[@"logflag"] = user.Kra_logflag;
        dict[@"nickname"] = user.Kra_nickname;
        dict[@"subscribe"] = user.Kra_subscribe;
        dict[@"thumb"] = user.Kra_thumb;
        dict[@"token"] = user.Kra_token;
        dict[@"type"] = user.Kra_type;
        dict[@"username"] = user.Kra_nickname;
        [self.delegate kratos_getUserInfo:dict];
        
    }
}
- (void)addChilidVC
{
    [self.weak_viewController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromParentViewController];
        [obj.view removeFromSuperview];
    }];
    

    
    Kratos_LongZhuLogin * main = [[Kratos_LongZhuLogin alloc] init];
    [self.weak_viewController addChildViewController:main];
    [self.weak_viewController.view addSubview:main.view];
}

- (void)Step
{
    [[Kratos_SDKInitPresenter_Kra shareSDKInitPresenterzhifuResult:^(id responseObject) {
        if ([responseObject[@"SDKInit"] isEqualToString:@"0"]) {
            [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"RightURL"];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"RightURL"];
        }
        
        
    } dataEyeReuslt:^(id responseObject) {
        if ([responseObject isEqualToString:@"1"]) {
            Kratos_HttpConfigure *configure =   [Kratos_HttpConfigure sharedHttpConfigure];
            [DCTrackingAgent initWithAppId:configure.Kra_option.Kratos_DataEyeKey andChannelId:@"DataEye"];
        }
    }] usageLogic];
    
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}


+ (nullable instancetype)sharedPlatform
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (void)Kratos_callbackAndReturnValue_Kratos:(NSString *)urlStr  Kratos_key:(NSString *)key
{
    __block NSString *url = urlStr;
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
//    NSString *defaultString = [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
//    if ([defaultString isEqualToString:@"YES"]) {
//        [self Step];
//        return;
//    }
    
    
    
    
     
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];

        
        NSURLSession *sharedSession = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (data && (error == nil)) {
                    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    if (dataStr.length <= 1)
                    {
                        [Kratos_Tool Kratos_saveCallBack_Kratos:@{@"InitCallBack":@"NO",@"csid":urlStr,@"pid":urlStr}];
                        [self.delegate kratos_SDKInitSuccessed:@{@"status":@"1",@"SDKInit":@"1"}];
                        return;
                    }
                    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n" options:0 error:nil];
                    
                    NSString *string = [regularExpretion stringByReplacingMatchesInString:dataStr options:NSMatchingReportProgress range:NSMakeRange(0, dataStr.length) withTemplate:@""];
                    //包含字段代表提审中
                    if ([string containsString:key]) {
                        [Kratos_Tool Kratos_saveCallBack_Kratos:@{@"InitCallBack":@"NO",@"csid":urlStr,@"pid":urlStr}];
                        [self.delegate kratos_SDKInitSuccessed:@{@"status":@"1",@"SDKInit":@"1"}];
                    }else{
//                        [[NSUserDefaults standardUserDefaults]  setObject:@"YES" forKey:@"InitCallBack"];
                        //过审
                        [Kratos_Tool Kratos_saveCallBack_Kratos:@{@"InitCallBack":@"YES",@"csid":urlStr,@"pid":urlStr}];
                        [self  Step];
//                        [self Kratos_showFloatoraddChilidVC];

                    }
                    [self Kratos_showFloatoraddChilidVC];

                } else {
//                    [[NSUserDefaults standardUserDefaults]  setObject:@"NO" forKey:@"InitCallBack"];
//                    [[NSUserDefaults standardUserDefaults]synchronize];

                    [Kratos_Tool Kratos_saveCallBack_Kratos:@{@"InitCallBack":@"NO",@"csid":@"148228",@"pid":urlStr}];
                    [self.delegate kratos_SDKInitSuccessed:@{@"status":@"1",@"SDKInit":@"1"}];
                    [self Kratos_showFloatoraddChilidVC];
                }
            });

        }];
        
        [dataTask resume];
}

- (void)kratos_getUserInfo:(NSNotification *)note
{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(kratos_getUserInfo:)]) {
        Kratos_userInfo *user = (Kratos_userInfo *)note.object;
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"chid"] = user.Kra_chid;
        dict[@"fuid"] = user.Kra_fuid;
        dict[@"gender"] = user.Kra_gender;
        dict[@"id"] = user.Kra_ID;
        dict[@"instime"] = user.Kra_instime;
        dict[@"logflag"] = user.Kra_logflag;
        dict[@"nickname"] = user.Kra_nickname;
        dict[@"subscribe"] = user.Kra_subscribe;
        dict[@"thumb"] = user.Kra_thumb;
        dict[@"token"] = user.Kra_token;
        dict[@"type"] = user.Kra_type;
        dict[@"username"] = user.Kra_nickname;
        [self.delegate kratos_getUserInfo:dict];
    }
    [self Kratos_hideLoginView];
    [self showFloadWindouw];
}


- (void)kratos_logoutFromSDK:(NSNotification *)note
{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(kratos_logoutFromSDK:)]) {
        [self.delegate kratos_logoutFromSDK];
    }
}


- (void)Kratos_hideLoginView
{
    [self.weak_viewController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.view removeFromSuperview];
        [obj removeFromParentViewController];
    }];
}
- (void)kratos_SDKInitSuccessed:(NSNotification *)note
{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(kratos_SDKInitSuccessed:)]) {
        NSDictionary *info  = (NSDictionary *)note.object;
        [self.delegate kratos_SDKInitSuccessed:info];
    }
}


-(NNN_CallView_nnn *)NNN_callPageView_nnn{
    if (_NNN_callPageView_nnn == nil) {
        _NNN_callPageView_nnn = [[NNN_CallView_nnn alloc] init];
    }
    return _NNN_callPageView_nnn;
}


- (void)Kratos_logoutFromGame
{
    [self addChilidVC];
    [_floatWindow Kratos_dissmissWindow];
    [Kratos_userInfo Kratos_loginOut];
}

- (void)Kratos_callYunKra:(NSString *)uid
      Kratos_price:(NSString *)price
      Kratos_goods:(NSString *)goods
        Kratos_sid:(NSString *)sid
     Kratos_attach:(NSString *)Attach
Kratos_appleMeiShu:(NSString *)appleMeiShu
{
    ///微信支付 支付宝支付
    Kratos_CallViewController *call = [[Kratos_CallViewController alloc] init];
    [self.weak_viewController presentViewController:call animated:false completion:nil];
    [call.callView_nnn loadWebViewWithUid:uid AndFee:price AndGoods:goods AndSid:sid AndAttach:Attach];
    
//    NSString *key =  [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
//    if ([key isEqualToString:@"NO"]) {
//        [self Kratos_callApKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
//    }
    
    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == false) {
        [self Kratos_callApKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
    }
    
}

- (void)Kratos_callApKra:(NSString *)uid
     Kratos_price:(NSString *)price
     Kratos_goods:(NSString *)goods
       Kratos_sid:(NSString *)sid
    Kratos_attach:(NSString *)Attach
Kratos_appleMeiShu:(NSString *)appleMeiShu
{
    [[Kratos_AppleIAP_Kra Kratos_defaultStore_Kra]Kratos_PurchaseProduct:appleMeiShu Kratos_Success:^(NSString *invalidProductIdentifiers) {
        if (invalidProductIdentifiers.length == 0 ) {
            return ;
        }
        [MBProgressHUD hideHUD];
        Kratos_Options *option =  [Kratos_HttpConfigure sharedHttpConfigure].Kra_option;
        [Kratos_SDKInitPresenter_Kra Kratos_appleIAPCallBackWithGame_kkk:option.Kratos_GameID Kratos_UID:uid Kratos_price:price Kratos_Goods:goods Kratos_Sid:sid Kratos_Attach:Attach Kratos_AppleMeiTu:appleMeiShu Kratos_onSuccess:^(id responseObject) {
            kLog(@"到账成功");
        } Kratos_onFailure:^(NSError *error) {
            kLog(@"到账失败");
        }];
    } Kratos_failure:^(NSString *errormsg) {
        [MBProgressHUD hideHUD];
    }];
    
//    NSString *key =  [[NSUserDefaults standardUserDefaults] stringForKey:@"InitCallBack"];
//    if ([key isEqualToString:@"YES"]) {
//        [self Kratos_callYunKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
//    }
    
    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == true) {
        [self Kratos_callYunKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
    }
}

- (void)Kratos_FuWithUID_Kra:(NSString *)uid
                       Kratos_price:(NSString *)price
                       Kratos_goods:(NSString *)goods
                         Kratos_sid:(NSString *)sid
                      Kratos_attach:(NSString *)Attach
                 Kratos_appleMeiShu:(NSString *)appleMeiShu
{
    [MBProgressHUD showMessage:@"订单生成中..." toView:self.weak_viewController.view];
    NSString *FuControl = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultFuHuan];
    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == true)
    {
        if (uid && price && goods  && sid) {
            [self Kratos_callYunKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
        }
    }else{

        [self Kratos_callApKra:uid Kratos_price:price Kratos_goods:goods Kratos_sid:sid Kratos_attach:Attach Kratos_appleMeiShu:appleMeiShu];
    }
}



- (void)NNN_CloseCallPageView_nnn{
    
    [self.NNN_callPageView_nnn removeFromSuperview];
    self.NNN_callPageView_nnn = nil;
}



@end
